<?php

namespace app\nideshop\service;


class Token
{
    public static $secret = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-=+";
    public static $key = 'www.jb51.net';
    
    //加密函数
    public static function lock_url($txt)
    {
        $chars = self::$secret;
        $nh = rand(0, 64);
        $ch = $chars[$nh];
        $mdKey = md5(self::$key . $ch);
        $mdKey = substr($mdKey, $nh % 8, $nh % 8 + 7);
        $txt = base64_encode($txt);
        $tmp = '';
        $i = 0;
        $j = 0;
        $k = 0;
        for ($i = 0; $i < strlen($txt); $i++) {
            $k = $k == strlen($mdKey) ? 0 : $k;
            $j = ($nh + strpos($chars, $txt[$i]) + ord($mdKey[$k++])) % 64;
            $tmp .= $chars[$j];
        }
        return urlencode($ch . $tmp);
    }

    //解密函数
    public static function unlock_url($txt)
    {
        $txt = urldecode($txt);
        $chars = self::$secret;
        $ch = $txt[0];
        $nh = strpos($chars, $ch);
        $mdKey = md5(self::$key . $ch);
        $mdKey = substr($mdKey, $nh % 8, $nh % 8 + 7);
        $txt = substr($txt, 1);
        $tmp = '';
        $i = 0;
        $j = 0;
        $k = 0;
        for ($i = 0; $i < strlen($txt); $i++) {
            $k = $k == strlen($mdKey) ? 0 : $k;
            $j = strpos($chars, $txt[$i]) - $nh - ord($mdKey[$k++]);
            while ($j < 0) $j += 64;
            $tmp .= $chars[$j];
        }
        return base64_decode($tmp);
    }

    public static function getUserId($token)
    {
        return self::unlock_url($token);
    }

    public static function create($userId) {
        return self::lock_url($userId);
    }
}
